package jp.gr.java_conf.genzo.wifinotify;

import jp.gr.java_conf.genzo.wifinotify.util.LogUtil;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;

public class WifiNotifyReceiver extends BroadcastReceiver {

	@SuppressWarnings("unused")
	private static final String TAG = WifiNotifyReceiver.class.getSimpleName();
	private static final String PREF_SSID_KEY = "SSID";
	private static final String PREF_CONNECT_TIME_KEY = "CONNECT_TIME";
	private static final String PREF_IP_KEY = "IP_ADDR";

//	private static boolean mFirst = true;



	/* (非 Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {

//		if (mFirst == true){
//			mFirst = false;
//			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//			long pre = pref.getLong(PREF_CONNECT_TIME_KEY, 0);
//			int minute = 60 * 12;//12時間以上経過している
//			if ((SystemClock.elapsedRealtime() - pre) > minute * 60 * 1000) {
//				writePreference(context, null, false);
//			}
//		}

		if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction()) ||
			WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())){
			NetworkInfo ni = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

			LogUtil.println("----------------------------------");
			if (ni.getType() != ConnectivityManager.TYPE_WIFI){
				LogUtil.println("WifiNotifyReceiver#onReceive NOT WIFI!! stat="+ ni.getState(), intent);
				return;
			}

			LogUtil.println("WifiNotifyReceiver#onReceive = " + ni.getState(), intent);

			if (ni.getType() == ConnectivityManager.TYPE_WIFI){
				WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				WifiInfo wi = wm.getConnectionInfo();

				if (wi == null) {
					return;
				}

				if (ni.getState() == NetworkInfo.State.CONNECTED){
					LogUtil.println("WifiNotifyReceiver#onReceive CONNECTED!!");

//					SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//					long pre = pref.getLong(PREF_SSID_PREFIX + wi.getSSID(), 0);
//					int minute = 5;//5分は何もしない

					if (wi.getSSID() == null) {
						LogUtil.println("WifiNotifyReceiver#onReceive wi.getSSID() == null!!");
						return;
					}
					AppSettings settings = new AppSettings(context);
					if (settings.getExcludeSSIDRow().indexOf(wi.getSSID()) >= 0) {
						LogUtil.println("WifiNotifyReceiver#onReceive ExcludeSSID!!");
						return;
					}

					SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
					String ssid = pref.getString(PREF_SSID_KEY, "");
					long pre = pref.getLong(PREF_CONNECT_TIME_KEY, 0);
					int minute = 60 * 24;//24時間以上経過している
					boolean diffTime = (SystemClock.elapsedRealtime() - pre) > minute * 60 * 1000;

					// 文字列が空なら、接続中じゃない
					if (TextUtils.isEmpty(ssid) || diffTime) {
						LogUtil.println("WifiNotifyReceiver#onReceive call service!! =" + ssid + " diffTime=" + (SystemClock.elapsedRealtime() - pre));
						writePreference(context, wi, true);

						Intent service = new Intent(context, NotifyService.class);
						service.putExtra(NotifyService.INTENT_NOTIFY_KEY, NotifyService.NOTIFY_ON);
						service.putExtra(NotifyService.INTENT_WIFI_INFO_KEY, wi);
						service.putExtra(NotifyService.INTENT_NETWORK_INFO_KEY, ni);
						context.startService(service);
					}else{
						LogUtil.println("WifiNotifyReceiver#onReceive no disconnected !!");
					}
				}else if (ni.getState() == NetworkInfo.State.DISCONNECTED){
					LogUtil.println("WifiNotifyReceiver#onReceive DISCONNECTED!!");

					Intent service = new Intent(context, NotifyService.class);
					service.putExtra(NotifyService.INTENT_NOTIFY_KEY, NotifyService.NOTIFY_OFF);
					service.putExtra(NotifyService.INTENT_NETWORK_INFO_KEY, ni);
					context.startService(service);

					writePreference(context, wi, false);
				}else{
					LogUtil.println("WifiNotifyReceiver#onReceive Other Stat!! =" + ni.getState());
					//よくわからない状態
//					Log.e(TAG, "OTHER NetworkInfo="+ ni);
				}
			}else{
				//Log.d(TAG, "NetworkInfo="+ ni);
			}
		}

	}

	private void writePreference(Context context, WifiInfo wi, boolean connenct) {
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = pref.edit();

		String ssid = connenct ? wi.getSSID() : "";
		long time = connenct ? SystemClock.elapsedRealtime() : 0;

		editor.putString(PREF_SSID_KEY, ssid);
		editor.putLong(PREF_CONNECT_TIME_KEY, time);
		int ip = connenct ? wi.getIpAddress() : 0;
		if (ip > 0) {
			editor.putInt(PREF_IP_KEY, ip);
		}
		editor.commit();

		LogUtil.println("WifiNotifyReceiver#writePreference! ssid=" +ssid + " time=" + time + " ip=" + ip);

	}
}